package com.ubs.training.server.dao.impl.jdbc;

import com.ubs.training.server.dao.UBSContactDao;
import com.ubs.training.server.dao.model.UBSContact;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xubuntu
 * Date: 8/21/12
 * Time: 5:19 AM
 * To change this template use File | Settings | File Templates.
 */
public class NamedParamUBSContactDaoImpl implements UBSContactDao {
    private DataSource ds;
    private NamedParameterJdbcOperations ops;

    public DataSource getDs() {
        return ds;
    }

    public void setDs(DataSource ds) {
        this.ds = ds;
        ops = new NamedParameterJdbcTemplate(ds);
    }


    @Override
    public List<UBSContact> getAll() {
        return ops.query("SELECT * FROM UBS_CONTACT", Collections.EMPTY_MAP, new BeanPropertyRowMapper<UBSContact>(UBSContact.class));
    }

    @Override
    public UBSContact getById(int id) {
        return ops.queryForObject("SELECT * FROM UBS_CONTACT WHERE ID =:id", Collections.singletonMap("id", id), new BeanPropertyRowMapper<UBSContact>(UBSContact.class));
    }

    @Override
    public void add(UBSContact u) {
        int id = ops.queryForInt("SELECT next value FOR cmstr_seq FROM dual", Collections.EMPTY_MAP);
        u.setId(id);
        ops.update("INSERT INTO ubs_contact VALUES(:id, :emp, :contact_type, :status, :client_id)", new BeanPropertySqlParameterSource(u));
    }

    @Override
    public void update(UBSContact u) {

        ops.update("UPDATE ubs_contact " +
                "SET emp=:emp, contact_type=:contact_type, status=:status " +
                "WHERE id=:id", new BeanPropertySqlParameterSource(u)
        );

    }

    @Override
    public void delete(int id){

        ops.update("DELETE FROM ubs_contact WHERE id =:id",Collections.singletonMap("id", id));

    }

    @Override
    public List<UBSContact> getAllUBSContactByClientId(int id) {
        return ops.query("SELECT * FROM UBS_CONTACT WHERE client_id=:id", Collections.singletonMap("id", id), new BeanPropertyRowMapper<UBSContact>(UBSContact.class));
    }
}
